import os
# 蔣勳 - 細說紅樓夢 - 第01回上
# 文件所在的目录
directory = r'E:\red'

# 遍历目录中的每个文件
for filename in os.listdir(directory):
    print(f'file: "{filename}" ')
    # 检查文件是否以'.wma'结尾
    if filename.endswith('.wma'):
        # 提取回次信息
        parts = filename.split(' - ')
        print(f'parts[2]: "{parts[2]}" ')
        print(f'len(parts) : "{len(parts) }" ')
        if len(parts) >= 3:
            episode_info = parts[2]  # '第XX回Y'
            episode_number = episode_info[1:3]  # XX
            part_indicator = episode_info[4:5]  # Y, 上或下
            print(f'episode_number : "{episode_number}" ')

            print(f'part_indicator: "{part_indicator}" ')
            # 根据上下部转换为01或02
            if part_indicator == '上':
                new_part_indicator = '01'
            elif part_indicator == '下':
                new_part_indicator = '02'
            else:
                continue  # 如果不是上或下，则跳过该文件

            # 创建新的文件名
            new_filename = f"{episode_number.zfill(2)}-{new_part_indicator}.wma"

            # 获取旧文件的完整路径
            old_file = os.path.join(directory, filename)
            # 获取新文件的完整路径
            new_file = os.path.join(directory, new_filename)

            # 重命名文件
            os.rename(old_file, new_file)
            print(f'Renamed "{filename}" to "{new_filename}"')